package com.nyist.myticket.web.common.controller;

import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.nyist.myticket.core.factory.GenerateCodeFactory;
import com.nyist.myticket.core.factory.GetTimeFactory;
import com.nyist.myticket.core.pay.alipay.AlipayProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author yangxiaogen
 * @date 2021/7/25 18:42
 */
@Slf4j
@RestController
@RequestMapping("/alipay")
public class AlipayController {
    @Autowired
    private AlipayProperty alipayProperty;

    @GetMapping(value = "/goAlipay")
    public void goAlipay(String merchantUserId, String merchantOrderId) throws Exception {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayProperty.getGatewayUrl(),
                alipayProperty.getAppId(),
                alipayProperty.getMerchantPrivateKey(),
                "json",
                alipayProperty.getCharset(),
                alipayProperty.getAlipayPublicKey(),
                alipayProperty.getSignType());

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperty.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayProperty.getNotifyUrl());

        // 商户订单号, 商户网站订单系统中唯一订单号, 必填
        //String out_trade_no = merchantOrderId;
        String out_trade_no = GenerateCodeFactory.snowflakeId().toString();

        // 付款金额, 必填 单位元
        String total_amount = "0.01";  // 测试用 1分钱
        // 订单名称, 必填
        String subject = "userName-付款用户[" + merchantUserId + "]";
        // 商品描述, 可空, 目前先用订单名称
        String body = subject;

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1h";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String alipayForm = "";
        try {
            alipayForm = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        log.info("支付宝支付 - 前往支付页面, alipayForm: \n{}", alipayForm);
    }

    @RequestMapping(value = "/returnSuccess")
    public String returnSuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("支付成功后的支付宝同步通知");

        String nowTime = GetTimeFactory.getNowTime();
        log.info("当前时间为:  {}",nowTime);

        log.info("当前时间为long:  {}",System.currentTimeMillis());

        // 进行页面的跳转, 展示支付成功等信息

        return "支付成功后的支付宝同步通知";
    }

    @RequestMapping(value = "/notifySuccess")
    public String notifySuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {

        log.info("支付成功后的支付宝异步通知");

        String nowTime = GetTimeFactory.getNowTime();
        log.info("当前时间为:  {}",nowTime);

        log.info("当前时间为long:  {}",System.currentTimeMillis());

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayProperty.getAlipayPublicKey(),
                alipayProperty.getCharset(),
                alipayProperty.getSignType()); //调用SDK验证签名

        if (signVerified) {//验证成功
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            if (trade_status.equals("TRADE_SUCCESS")) {
                // 当交易状态为成功以后的具体自己系统的业务处理, 比如更改订单的支付状态等 支付相关信息
                //String merchantReturnUrl = paymentOrderService.updateOrderPaid(out_trade_no, CurrencyUtils.getYuan2Fen(total_amount));
                //notifyFoodieShop(out_trade_no,merchantReturnUrl);
            }

            log.info("************* 支付成功(支付宝异步通知) - 时间: {} *************", DateUtil.today());
            log.info("* 订单号: {}", out_trade_no);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
            log.info("* 交易状态: {}", trade_status);
            log.info("*****************************************************************************");

            return "success";
        } else {
            //验证失败
            log.info("验签失败, 时间: {}", DateUtil.today());
            return "fail";
        }
    }

}
